package com.vehicle.realm;

import com.vehicle.pojo.User;
import com.vehicle.service.UserService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class VehiclesRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    private Logger logger=Logger.getLogger(this.getClass());

    @Override
    public String getName() {
        return "vehiclesRealm";
    }


    //清理缓存
    public void clearAuthz(){
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("授权认证————————————");
        String uname=(String) principalCollection.getPrimaryPrincipal();
        Set<String> rolesNameByUname = userService.findRolesNameByUname(uname);
        Set<String> percodesByUname = userService.findPercodesByUname(uname);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(rolesNameByUname);
        info.setStringPermissions(percodesByUname);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("登录认证++++++++++++++++++++++");

        String uname= (String) authenticationToken.getPrincipal();
        User user = userService.findUserByTelephone(uname);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(uname,user.getPassword(),this.getName());
        return info;
    }

}
